'''
list: list of station list 
    station list :
    useful index :
        1 Chinese name 
        2 station code for api 
        4 all first letter of pinyin of Chinese character


'''
'''
    TODO 
            add Filter 
'''
import GetPage  

class StationQuery():
    def __init__(self,StationCodeTxt,encoding='utf-8'):
        self.list=[]
        self.pyhead={}
        self.pyfull={}
        self.Station={}
        self.__FromID=''
        self.__ToID=''
        self.__date=''
        self.Readlist(StationCodeTxt)
    def Readlist(self,StationCodeTxt,encoding='utf-8'):
        with open(StationCodeTxt,"r",encoding=encoding) as dict:
            for line in dict.readlines():
                list=line.split("|")[:-1]
                if (not list[4] in self.pyhead):
                    self.pyhead[list[4]]=[]
                self.pyhead[list[4]].append(list[2])
            
        
                if (not list[3] in self.pyfull):
                    self.pyfull[list[3]]=[]
                self.pyfull[list[3]].append(list[2])
         
                self.Station[list[2]]=list[1]

        #ordict=dict.fromkeys(string.ascii_lowercase,{})

    def getStationID(self,query):
        '''
        Get station's ID by it's pingying, return an empty str if doesn't match 
        pingying could be beijingxi or bjx 
        ''' 
        result=[]
        query=query.lower()
        if (query in self.pyhead):
            result=result+ self.pyhead[query]
        
        if (query in self.pyfull):
            result=result+self.pyfull[query]
        if (len(result)>1):
            print("It is more than one station that matchs {}:".format(query))
        
            for i  in range(len(result)):
                print("[{}]:{}".format(i+1,self.getName(result[i])))

            i=int(input("Enter the number to chose:\n"))-1
            return result[i]
        elif (len(result)):
            return result[0]
    
        else:
            return ''
            
    def getName(self,ID):
        '''
        Get station's chinese name by ID
        '''
        if(ID in self.Station):
            return self.Station[ID]
        else:
            return ''
    @property
    def FromID(self):
        return self.__FromID
    @FromID.setter
    def FromID(self,value):
        if (value in self.Station):
            self.__FromID=value
            self.FromName=self.getName(value)
        else:
            print("Set FromID failed, ID:{} doesn't exists!".format(value))
    @property
    def ToID(self):
        return self.__ToID
    @ToID.setter
    def ToID(self,value):
        if (value in self.Station):
            self.__ToID=value
            self.ToName=self.getName(value)
        else:
            print("Set ToID failed,  ID:{}  doesn't exists!".format(value))
            
    @property
    def Date(self):
        return self.__date
    @Date.setter
    def Date(self,value):
        year=int(value[:4])
        mon=int(value[5:7])
        day=int(value[8:10])
        if(year>=2017):
            if(mon>0 and mon<13 ):
                if(day>0 and day<32 ):
                    self.__date="{}-{:0>2}-{:0>2}".format(year,mon,day)

                else:
                    print("Wrong day: {}!".format(day))
            else:
                print("Wrong mon: {}!".format(mon))
        else:
            print("Wrong year: {}!".format(year))
       
            
def getinfo(): 
    s=StationQuery("12306_StationCode.txt")

    while(1):
        start=input("Where will you take train?\n(bjx represent for station BeiJingXi)\n")
        s.FromID=s.getStationID(start)
        if (s.FromID):
            break
        print("Sorry, I can't find the station {}. Is it a spelling mistake?".format(start))
    print("You have selected {} .".format(s.FromName))
    while(1):
        dest=input("Where are your destination?")
        s.ToID=s.getStationID(dest)
        if (s.ToID):
            break
        print("Sorry, I can't find the station {}. Is it a spelling mistake?".format(dest))
    print("You have selected {} .".format(s.ToName))

    while(1):
        s.Date=(input("What is the date you will take train?\n"))
        if(s.Date):
            break
    print("\n{} -> {}".format(s.FromName,s.ToName))
    print(s.Date)
    return s
    


def main():
    s=getinfo()

    spd=GetPage.QuerySpider(s.Date,s.FromID,s.ToID)

    spd.query()
    print()
    print("日期：{}\t{}站 --> {}站".format(s.Date,s.FromName,s.ToName))
    print('-'*20)
    for train in spd.TrainList:
        seat=train.Seat
        # if ((seat.SecSeat !='无' or seat.SecSeat) and (seat.NoSeat or seat.NoSeat!='无') ):
            # continue
        # if(int(train.FromTime[:2])<14):
            # continue
        if (train.From!=s.FromID or train.To != s.ToID):
            continue
        print("[{}]:     {} - {}    耗时:{} ".format(train.Name,train.FromTime,train.ToTime,train.CostTime))
        print("一等座: {: <4}二等座: {: <4}无座: {: <4} ".format(seat.FriSeat,seat.SecSeat,seat.NoSeat))
        print()

if __name__ == '__main__':
    main()
